#module
from moviepy.editor import *
import pygame,os


#class
class FormError(Exception):
    def __init__(self, message):
        self.message = message
 
    def __str__(self):
        return self.message


#fun
def b(a):
    while ("\n"in a):
        a=a[0:a.index("\n")]+a[a.index("\n")+1:]
    return a
def file_processing(file):
    o={}
    with open(file,'r',encoding="UTF-8") as f:
        for a in f:
            if ":" in a and "#" != a[0]:
                a=b(a)
                k={}
                if ("(" in a and ")" in a and ";" in a):
                    s=a[a.index(":")+1:][1:-1]+";"
                    l=[]
                    v=""
                    for x in s:
                        if x==";":
                            l.append(v)
                            v=""
                            continue
                        v=v+x
                    for x in l:
                        if "path" not in x and "font" not in x:
                            k[x[0:x.index("=")]]=x[x.index("=")+1:]
                        else:
                            if "/" not in x[x.index("=")+1:]:
                                z="file_need/otherfile/"+x[x.index("=")+1:]
                            else:
                                z=x[x.index("=")+1:]
                            k[x[0:x.index("=")]]=z
                    o[a[0:a.index(":")]]=k
                else:
                    if "path" in a[0:a.index(":")]:
                        if "/" not in a[a.index(":")+1:]:
                            z="file_need/otherfile/"+a[a.index(":")+1:]
                        else:
                            z=a[a.index(":")+1:]
                        o[a[0:a.index(":")]]=z
                    else:o[a[0:a.index(":")]]=a[a.index(":")+1:]
    return o
def textshow(file):
    screen = pygame.display.set_mode((screen_width, screen_height))
    o=file_processing(file)
    if o=={}:
        raise FormError("为空")
    try:exec(o["exec_beforewhile"])
    except:pass
    #background=pygame.image.load(o["pic"]).convert()
    code0,code1,code2,code3,code4,code5="","","","","",""
    pi=[]
    for i in o:
        if "pic" in i:
            pi.append(i)
    for i in pi:
        code0+=i+"=pygame.image.load(\""+o[i]["path"]+"\").convert()\n"
        code1+=i+"=pygame.transform.scale("+i+","+o[i]["size"]+")\n"
        code2+="screen.blit("+i+","+o[i]["pos"]+")\n"
    te=[]
    for i in o:
        if "text" in i:
            te.append(i)
    for i in te:
        code3+=i+"=pygame.font.Font('"+o[i]["font"]+"',"+o[i]["size"]+").render('"+o[i]["text"]+"', "+o[i]["optimize"]+","+o[i]["color"]+")\n"
        code4+=i+"_rect="+i+".get_rect()\n"+i+"_rect."+o[i]["pos_type"]+"="+o[i]["pos"]+"\n"
        code5+="screen.blit("+i+","+i+"_rect)\n"
    exec(code0)
    exec(code3)
    running = True
    fps=0
    while running:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False
            elif event.type == pygame.MOUSEBUTTONUP:
                running = False
            elif event.type == pygame.KEYDOWN:
                if event.key == pygame.K_ESCAPE:
                    running = False
                if event.key == pygame.K_SPACE:
                    running = False
        #scaled_image = pygame.transform.scale(background, (screen_width, screen_height))
        exec(code1)
        #screen.blit(scaled_image, (0, 0))
        exec(code2)
        exec(code4)
        exec(code5)
        try:exec(o["exec_inwhile"])
        except:pass
        pygame.display.flip()
        fps+=1
    try:exec(o["exec_afterwhile"])
    except:pass
def movieshow(file):
    f = file_processing(file)
    video_path = f["path"]
    if "time" in f and (f["time"][0]=="("and f["time"][-1]==")"):
        clip = VideoFileClip(video_path).subclip(f["time"][1:f["time"].index(",")], f["time"][f["time"].index(",")+1:-1]).resize((screen_width,screen_height))
    else:
        clip = VideoFileClip(video_path).resize((screen_width,screen_height))
    clip.preview()


#var
files = ["file_need/"+f for f in os.listdir("file_need/") if os.path.isfile(os.path.join("file_need/", f))]
movie=[f for f in files if ("movie" in f) if (f[f.index("movie")+5] in [str(i) for i in range(0,10,1)])]
text=[f for f in files if ("text" in f) if (f[f.index("text")+4] in [str(i) for i in range(0,10,1)])]
with open('file_need/time.txt','r',encoding="UTF-8") as file:
    time=[b(line) for line in file]
time=[tm+".txt" for tm in time if tm != ""]


#main
pygame.init()
screen_info = pygame.display.Info()
screen_width = screen_info.current_w
screen_height = screen_info.current_h
pygame.display.set_caption('节目背景')
for tm in time:
    if "file_need/"+tm in text:
        try:
            textshow("file_need/"+tm)
        except:pass
    if "file_need/"+tm in movie:
        try:
            movieshow("file_need/"+tm)
        except:pass
pygame.quit()